import re,json
from chats.models import ChatData
from django.contrib.auth import authenticate
from django.db.models import Q
from django.http import JsonResponse,HttpResponseForbidden
import time
from django.shortcuts import render
from users.jwt import check_keys, encode_key
# Create your views here.
from django.views import View
from users.models import User,Friend
from utails.pushfile import request_to


class RequestFriends(View):
    def get(self, request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('403')

        friends = user.user_b.filter(status=0)
        content = []
        for i in friends:
            content.append({
                'id':i.user_a.id,
                'username':i.user_a.username,
                'userimg':i.user_a.default_image,
                'new_data':i.mew_data,
                'time':i.create_time
            })
        return JsonResponse(content, safe=False)

    def post(self, request):
        '''好友申请'''
        jsondict = json.loads(request.body.decode())
        userid = jsondict.get('userid')
        friend = jsondict.get('friendid')
        new_data= jsondict.get('new_data')
        if not all([userid, friend, new_data]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            friend = User.objects.get(id=friend)
        except:
            return HttpResponseForbidden('403')

        try:
            fexists = Friend.objects.get(Q(user_a=user,user_b=friend)|Q(user_a=friend, user_b=user))
        except:
            print('\033[0;34m 好友未存在 申请成功 \033[')
        else:
            return JsonResponse({'code':'401'})

        try:
            Friend.objects.create(
                user_a=user,
                user_b=friend,
                mew_data=new_data,
                status=0
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code':'400'})
        return JsonResponse({'code':'200'})

    def put(self, request):
        '''同意'''
        jsondict = json.loads(request.body.decode())
        userid = jsondict.get('userid')
        friend = jsondict.get('friendid')
        if not all([userid, friend]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            friend = User.objects.get(id=friend)
        except:
            return HttpResponseForbidden('403')
        try:
            friends = user.user_b.get(user_a=friend)
            # friends = Friend.objects.get(user_a=friend,user_b=user)
            friends.status = 1
            friends.save()
        except:
            return JsonResponse({'code':'400'})
        # 同意后的话
        try:
            ChatData.objects.create(
                chat_a=user,
                chat_bir=friend,
                types=0,
                chat_data='我已同意好友申请，现在一起来聊天吧',
                status=0
            )
        except:
            print('\033[0;34m err white user \033[')


        return JsonResponse({'code':'200'})

    def delete(self, request):
        '''拒绝'''
        jsondict = json.loads(request.body.decode())
        userid = jsondict.get('userid')
        friend = jsondict.get('friendid')
        if not all([userid, friend]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            friend = User.objects.get(id=friend)
        except:
            return HttpResponseForbidden('403')
        try:
            friends = user.user_b.get(user_a=friend)
            friends.status = 2
            friends.save()
        except:
            return JsonResponse({'code': '400'})
        return JsonResponse({'code': '200'})


class PushUserimg(View):
    def post(self, request):
        userid = request.POST.get('userid', None)
        file = request.FILES.get('file')
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('403')
        # 上传图片
        ord_img = user.default_image
        res = request_to(file,'',0, 'ord_img')
        # 保存
        try:
            user.default_image = res
            user.save()
        except:
            return JsonResponse({'code':'400'})

        return JsonResponse({'code':'200'})

class Userdetails(View):
    '''用户信息'''
    def get(self, request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('403')

        # 校验keys token

        # 返回结果
        content = {
            'id':user.id,
            'username':user.username,
            'userimg':user.default_image,
            'email':user.email,
            'phone':user.tel,
            'birthday':user.birthday,
            'register':user.date_joined,
            'text':user.text,
            'gender':user.gender
        }
        return JsonResponse(content)

    def post(self,request):
        jsondict = json.loads(request.body.decode())
        userid = jsondict.get('userid')
        types = jsondict.get('types')
        datas = jsondict.get('datas')
        if not all([userid, types]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('403')

        try:
           if types == '昵称':
               user.username = datas
           elif types == '邮箱':
               user.email = datas
           elif types == '签名':
               user.text = datas
           elif types == '电话':
               user.tel = datas
           elif types == '生日':
               user.birthday = datas
           elif types == '性别':
               user.gender = datas
           else:
               return HttpResponseForbidden('403')
           user.save()
        except:
            return JsonResponse({'code':'400'})

        return JsonResponse({'code':'200'})

class UserMain(View):
    '''用户首页'''
    def get(self, request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('403')

        content = {
            'id':user.id,
            'username':user.username,
            'userimg':user.default_image,
            'text':user.text,
            'gender':user.gender,
            'email':user.email
        }
        return  JsonResponse(content)


class UserCheck(View):
    '''校验用户信息'''
    def get(self, request, pk):
        # 获取header request.HETA.get('HTTP_NAME') '-' 自动转化我 '_'
        keys = request.META.get('HTTP_AUTHORIZATION', None)
        if keys==None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=pk)
        except:
            return HttpResponseForbidden('400')

        keydata = check_keys(keys)
        if keydata != 'ok':
            return HttpResponseForbidden('400')
        keys = encode_key(user.email, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()+1000*60*60*24))

        content = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'tel': user.tel,
            'userimg': user.default_image,
            'text': user.text,
            'keys': keys
        }

        return JsonResponse(content)


class LoginView(View):
    """用户登录"""

    def get(self, request):
        """提供用户登录页面"""
        return JsonResponse({'code':'400'})

    def post(self, request):
        """实现用户登录逻辑"""
        jsondict = json.loads(request.body.decode())

        # 接收参数
        username = jsondict.get('username')
        password = jsondict.get('password')

        # 校验参数
        if not all([username, password]):
            return HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_\u4e00-\u9fa5]{3,20}$', username):
            return HttpResponseForbidden('请输入正确的用户名或手机号')

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('密码最少8位，最长20位')

        # 认证用户:使用账号查询用户是否存在，如果用户存在，再校验密码是否正确
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code':'登录失败'})

        kyes = encode_key(user.email,time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

        content = {
            'id':user.id,
            'username': user.username,
            'email': user.email,
            'tel': user.tel,
            'userimg': user.default_image,
            'text': user.text,
            'keys':kyes
        }
        # 响应结果:重定向到首页
        return JsonResponse(content)


class Register(View):
    def get(self, request):
        return HttpResponseForbidden('401')

    def post(self, request):
        """实现用户注册业务逻辑"""
        jsindict = json.loads(request.body.decode())
        # 接收参数：表单参数
        username = jsindict.get('username')
        password = jsindict.get('password')
        tel = jsindict.get('tel')
        email = jsindict.get('email')

        # 校验参数：前后端的校验需要分开，避免恶意用户越过前端逻辑发请求，要保证后端的安全，前后端的校验逻辑相同
        # 判断参数是否齐全:all([列表])：会去校验列表中的元素是否为空，只要有一个为空，返回false
        if not all([username, password, tel, email]):
            return HttpResponseForbidden('缺少必传参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_\u4e00-\u9fa5]{3,20}$', username):
            return HttpResponseForbidden('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('请输入8-20位的密码')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', tel):
            return HttpResponseForbidden('请输入正确的手机号码')
        if not re.match(r'^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$',email):
            return HttpResponseForbidden('邮箱错误')

        try:
            user = User.objects.create_user(username=username, password=password, tel=tel, email=email)
        except:
            return JsonResponse({'code':'400'})

        # keys
        kyes = encode_key(user.email,time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

        content = {
            'id':user.id,
            'username':user.username,
            'email':user.email,
            'tel':user.tel,
            'userimg':user.default_image,
            'text':user.text,
            'keys':kyes
        }

        # 响应结果:重定向到首页
        return JsonResponse(content)

def err(request):
    return JsonResponse({'code':'200'})


